#include <stdio.h>
#include <signal.h>
#include "ax_common.h"
#include "netd.h"

void netd_unit_test();
extern void init_net();


void sig_term(int signo)
{
	if (signo == SIGTERM) {
		netd_abort("catch SIGTERM");
	} else if (signo == SIGINT) {
		netd_abort("catch SIGINT");
	}
}

void sig_hup(int signo)
{
	netd_abort("catch SIGHUP");
}

void init_signal()
{
	signal(SIGTERM, sig_term);
    signal(SIGINT, sig_term);
    signal(SIGHUP, sig_hup);
}

int main(int argc, char ** argv)
{
	char ch;
	netd_log(LOG_CRITICAL, "netd process started");
	
	//init shell args
	while ((ch = getopt(argc, argv, "td:c")) != -1)
	{
		switch(ch)
		{
		//run unit test
		case 't':
			netd_unit_test();
			return 0;
		//run program, definite config file
		case 'c':
			if (NetdConfig::reload_config(optarg) != 0) {
				return 0;  //config file error
			}
			break;
		default:
			break;
		}

	}	
	
	//start running
	init_signal();
	init_net();
	dispatch();
	netd_log(LOG_CRITICAL, "netd exit normally");
	return 0;
}

void netd_log(int level, const char* fmt, ...)
{
	static char file[1024];	
	va_list args;
    
	va_start(args, fmt);
	sprintf(file, "%s/%s", NetdConfig::log_path, NetdConfig::log_name);
    ax_vlogf(file, fmt, args);
    va_end(args);
	if (level == LOG_CRITICAL) {
		va_start(args, fmt);
		sprintf(file, "%s/%s", NetdConfig::log_path, NetdConfig::log_debug_name);
		ax_vlogf(file, fmt, args);
		va_end(args);
	}
}

void netd_abort(const char* reason)
{
	netd_log(LOG_CRITICAL, "netd process abort. reason: %s", reason);
	exit(-1);
}

//unit test
void netd_unit_test()
{
	RUN_UTEST(conn_mgr);
}
